package org.demo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by tangwy on 2017/10/11.
 */
public class NioServer {
    private String ip;
    private int port;
    private ServerSocketChannel channel;
    private Selector selector;
    private SocketAddress address;
    private volatile boolean stop;

    public NioServer(int port) {
        this.port = port;
        address = new InetSocketAddress(port);
    }

    public NioServer(String ip, int port) {
        this(port);
        this.ip = ip;
        address = new InetSocketAddress(ip, port);
    }

    private void init() throws IOException {
        channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        channel.socket().bind(address);
        //serverSocket.
        this.selector = Selector.open();
        channel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void start() throws IOException {
        this.init();
        while (!stop) {
            int select = selector.select(500);
            if (select > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    process(key);
                }
            }

        }
    }

    private void process(SelectionKey key) throws IOException {
        if(!key.isValid()){
            return;
        }
        if(key.isAcceptable()){
            ServerSocketChannel ssc=(ServerSocketChannel)key.channel();
            SocketChannel channel = ssc.accept();
            channel.configureBlocking(false);
            channel.register(selector,SelectionKey.OP_READ);
        }else if(key.isReadable()){
            //read
        }else if(key.isWritable()){
            //write
        }
    }
}
